package CreationPattern.FactoryMethod;

/**
 * @Classname : SinglePhoneFactory
 * @Description : 创建型-简单工厂
 * 适用场景：产品类较少，且不同产品初始化入参相同
 * @Author : chentianyu
 * @Date 2023/1/4 23:30
 */

public class PhoneSimpleFactory {

    /**
     * 枚举实现
     */
    public PhoneProduct createMobilePhone(PhoneProductEnum e) {
        PhoneProduct mobilePhoneProduct = null;
        switch (e) {
            case HUAWEI :
                mobilePhoneProduct = new HUAWEI();
                break;
            case XIAOMI:
                mobilePhoneProduct = new XIAOMI();
                break;
            default:
                break;
        }
        return mobilePhoneProduct;
    }

    public void run(PhoneProductEnum e) {
        PhoneProduct phoneProduct = createMobilePhone(e);
        phoneProduct.run();
    }


    /**
     * 反射实现
     */
    public <T extends PhoneProduct> T createMobilePhone(Class<T> c) {
        T product = null;
        try {
            // newInstance()方法要求类必须有无参构造器
            product = c.newInstance();
        } catch (Exception e) {
            // 异常处理
            throw new RuntimeException(e);
        }
        return product;
    }

    public <T extends PhoneProduct> void run(Class<T> c) {
        PhoneProduct phoneProduct = createMobilePhone(c);
        phoneProduct.run();
    }

}

